

package com.hulk.ratel.common.component;


import com.baomidou.mybatisplus.core.metadata.IPage;

import com.hulk.ratel.common.constant.Constants;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 响应信息主体
 *
 * @param <T>
 * @author hulk
 */
@Slf4j
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class R<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	private int code;

	@Getter
	@Setter
	private String msg;

	@Getter
	@Setter
	private T data;




	public static <T> R<T> ok() {
		return restResult(null, Constants.SUCCESS, null);
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, Constants.SUCCESS, null);
	}

	public static <T> R<T> ok(String msg,T data) {
		return restResult(data, Constants.SUCCESS, msg);
	}

	public static <T> R<T> failed() {
		return restResult(null, Constants.FAILED, null);
	}

	public static <T> R<T> failed(String msg) {
		return restResult(null, Constants.FAILED, msg);
	}

	public static <T> R<T> failed(T data) {
		return restResult(data, Constants.FAILED, null);
	}

	public static <T> R<T> failed( String msg, T data) {
		return restResult(data, Constants.FAILED, msg);
	}

	public static <T> R<T> failed(int code, String msg) {
		return restResult(null, code, msg);
	}

	public static <T> R<T> failed( int code, String msg,T data) {
		return restResult(data, code, msg);
	}


	private static <T> R<T> restResult(T data, int code, String msg) {
		R<T> api = new R<>();
		api.covert(api, data,  code,  msg);
		return api;
	}

	private  <T> R<T> covert(R api ,T data, int code, String msg){
		api.setCode(code);
		api.setMsg(msg);
		api.setData(data);
		if(data instanceof IPage){
			log.info("返回API信息，code: [{}], msg: [{}],  IPage: [{}]",code,msg,((IPage<?>) data).getRecords());
		}else {
			log.info("返回API信息，code: [{}], msg: [{}],  data: [{}]",code,msg,data);
		}

		return api;
	}

}
